package request_log

import (
	"encoding/json"
	"gitee.com/dreamwood/ez-go/db/mgo"
	"gitee.com/dreamwood/ez-go/ez"
	"time"
)

func init() {
	ez.AddFinisher("RequestLog", func(session *ez.Session) {
		for _, process := range session.Timer.Process {
			session.AddSessionLog(
				"timer", process.Name, process.CostString, session.ChainKey)
		}
		log := &RequestLog{
			Session: session.ChainKey,
			Url:     session.Input.Request.URL.Path,
			Logs:    session.Logs,
		}
		e := ez.NsqProducer.Publish(ez.EzTopicRequestLog, log.ToBytes())
		if e != nil {
			ez.LogToConsole(e.Error())
		}
	})
}

type RequestLog struct {
	mgo.BaseDoc `bson:"-" json:"-"`
	Id          int64            `json:"id" bson:"id,omitempty"`
	Url         string           `json:"url" bson:"url"`
	Session     string           `json:"session" bson:"session"`
	Logs        []*ez.SessionLog `json:"logs" bson:"logs"`
	CreateAt    time.Time        `json:"createAt" bson:"createAt"`
	UpdateAt    time.Time        `json:"updateAt" bson:"updateAt"`
	DeleteAt    *time.Time       `json:"deleteAt" bson:"deleteAt"`
}

func (this *RequestLog) DocName() string { return "RequestLog" }
func (this *RequestLog) GetId() int64    { return this.Id }
func (this *RequestLog) SetId(id int64)  { this.Id = id }
func (this *RequestLog) Save() error {
	if this.Id == 0 {
		this.CreateAt = time.Now()
		this.UpdateAt = time.Now()
		return this.GetFactory().Create(this)
	} else {
		this.UpdateAt = time.Now()
		return this.GetFactory().Replace(this)
	}
}
func (this *RequestLog) ToString() string {
	return string(this.ToBytes())
}
func (this *RequestLog) ToBytes() []byte {
	data, e := json.Marshal(this)
	ez.Try(e)
	return data
}
func (this *RequestLog) ClearRelationsBeforeSave() mgo.Doc {
	return this
}
